package com.ymttest.database.sharding;

import io.shardingjdbc.core.api.algorithm.sharding.ListShardingValue;
import io.shardingjdbc.core.api.algorithm.sharding.ShardingValue;
import io.shardingjdbc.core.api.algorithm.sharding.complex.ComplexKeysShardingAlgorithm;

import java.util.Collection;

/**
 */
public abstract class ComplexKeysAlgorithm
		implements
			ComplexKeysShardingAlgorithm {

	@Override
	public Collection<String> doSharding(
			final Collection<String> availableTargetNames,
			final Collection<ShardingValue> shardingValues) {
		if (shardingValues != null && shardingValues.size() > 0) {
			ListShardingValue<Long> listShardingValue = null;
			if (shardingValues.size() == 1) {
				ShardingValue shardingValue = shardingValues.iterator().next();
				if (shardingValue instanceof ListShardingValue) {
					listShardingValue = (ListShardingValue<Long>) shardingValue;
				}
			} else {
				for (ShardingValue value : shardingValues) {
					if (value instanceof ListShardingValue) {
						ListShardingValue<Long> lsv = (ListShardingValue<Long>) value;
						//同一个表中order_id main_order_id都有的时候 按order_id分库分表
						if (lsv.getColumnName().equals(" ")) {
							listShardingValue = lsv;
							break;
						}
						listShardingValue = lsv;
					}
				}
			}
			if (listShardingValue != null) {
				return doInSharding(availableTargetNames, listShardingValue);
			}
		}

		throw new UnsupportedOperationException();
	}

	protected abstract Collection<String> doInSharding(
			final Collection<String> availableTargetNames,
			final ListShardingValue<Long> shardingValue);
}
